package rahmath.sharif.docrypt;

import java.io.File;

import rahmath.sharif.docrypt.constant.DocryptConstants;
import rahmath.sharif.docrypt.entity.Vault;
import rahmath.sharif.docrypt.util.AESCryptor;
import rahmath.sharif.docrypt.util.DocryptUtil;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class VaultsActivity extends ListActivity implements DocryptConstants {

	@TargetApi(11)
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vaults);
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		setListAdapter(new ArrayAdapter<Vault>(this, R.layout.list_item_vault,
				DocryptUtil.getVaultsFromSD()));
		final ListView listView = getListView();
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long length) {
				final Vault vault = (Vault) listView
						.getItemAtPosition(position);
				LayoutInflater inflater = LayoutInflater
						.from(VaultsActivity.this);
				final View authenticationView = inflater.inflate(
						R.layout.alert_dialog_vault_authentication, null);
				final EditText editTextVaultPassword = ((EditText) authenticationView
						.findViewById(R.id.editTextAlertVaultPassword));
				editTextVaultPassword
						.setOnFocusChangeListener(new OnFocusChangeListener() {
							public void onFocusChange(View v, boolean hasFocus) {
								editTextVaultPassword.post(new Runnable() {
									public void run() {
										InputMethodManager inputMethodManager = (InputMethodManager) VaultsActivity.this
												.getSystemService(Context.INPUT_METHOD_SERVICE);
										inputMethodManager
												.showSoftInput(
														editTextVaultPassword,
														InputMethodManager.SHOW_IMPLICIT);
									}
								});
							}
						});
				editTextVaultPassword.requestFocus();
				final DialogInterface.OnClickListener passwordDialogListener = new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String userEnteredPassword = editTextVaultPassword
								.getText().toString();
						switch (which) {
						case DialogInterface.BUTTON_POSITIVE:
							if (AESCryptor.validatePassword(256,
									vault.getPassword(), userEnteredPassword)) {
								Intent intent = new Intent(VaultsActivity.this,
										DatasActivity.class);
								intent.putExtra(VAULT_FILE_NAME,
										vault.getVaultFileName());
								intent.putExtra(VAULT_PASSWORD,
										userEnteredPassword);
								startActivity(intent);
							} else {
								Toast.makeText(
										getApplicationContext(),
										getString(R.string.vaultAuthenticationFailed),
										Toast.LENGTH_SHORT).show();
								dialog.dismiss();
							}
							break;
						case DialogInterface.BUTTON_NEGATIVE:
							dialog.dismiss();
							break;
						}
					}
				};
				new AlertDialog.Builder(VaultsActivity.this)
						.setCancelable(false)
						.setTitle("Vault Authentication")
						.setMessage("Vault : " + vault.getName())
						.setPositiveButton("Authenticate",
								passwordDialogListener)
						.setNegativeButton("Cancel", passwordDialogListener)
						.setView(authenticationView).show();
			}
		});
		File docryptDir = DocryptUtil.getDocryptDir(DOCRYPT_VAULTS);
		if (!docryptDir.exists() || docryptDir.list().length == 0) {
			DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						Intent intentCreateVault = new Intent(
								VaultsActivity.this, CreateVaultActivity.class);
						startActivity(intentCreateVault);
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						finish();
						break;
					}
				}
			};

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setCancelable(false);
			builder.setMessage(
					"There are no vaults available. Do you want to create one?")
					.setPositiveButton("Yes", dialogClickListener)
					.setNegativeButton("No", dialogClickListener).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_vaults, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.createVault:
			Intent intentCreateVault = new Intent(VaultsActivity.this,
					CreateVaultActivity.class);
			startActivity(intentCreateVault);
			return true;
		case R.id.help:
			Intent helpActivity = new Intent(this, HelpActivity.class);
			startActivity(helpActivity);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
